/*防止和laravel的blade冲突*/
var todoApp = angular.module('laravelTodo', [], function($interpolateProvider) {
        $interpolateProvider.startSymbol('<%');
        $interpolateProvider.endSymbol('%>');
});

/* 定义controller */
todoApp.controller(
    'TodoCtrl',
    // ["$scope","$http","$timeout", function($scope, $http, $timeout){
    function ($scope, $http) {
        //init or countItem will be wrong
        $scope.items = 0;

        //timer
        var updateClock = function() {
            $scope.currentTime = new Date();
        };

        var timer = setInterval(function() {
            $scope.$apply(updateClock);
        }, 1000);
        updateClock();

        //list
        $http.get('todos').success(function (todos) {
            $scope.items = todos;
        }).error(function(data){
            console.log(data);
        });

        //add
        $scope.addItem = function() {
            if  (!$scope.itemEntry) return false;
            // backend api
            $http.post('todo', {title: $scope.itemEntry}).success(function(data, status){
                if (data) {
                    //push to item list
                    $scope.items.push({id: data, title: $scope.itemEntry, completed: false});
                    $scope.itemEntry = '';
                    console.log($scope.items);
                } else {
                    console.log('issue occured the status is ' + status + 'data is ' + data);
                }
            }).error(function(data){
                console.log(data);
            });
        }

        //update
        $scope.updateStatus = function(todo) {
            $http.put('todo/' + todo).success(function(data, status){
                if (data) {
                    console.log(todo + 'status changed');
                } else {
                    console.log('issue occured in update status is ' + status + 'data is ' + data);
                }
            }).error(function(data){
                console.log(data);
            });
        }

        //delete
        $scope.clearTodo = function() {
            $scope.items = _.filter($scope.items, function(item) {

                if(item.completed) {
                    $http.delete('todo/' + item.id).error(function(data, status) {
                        console.log(data);
                    });
                }

                return !item.completed;
            });
        }



        $scope.progressbarItem = function() {
            return ($scope.completedTodo()*100)/$scope.countItem();
        }

         $scope.countItem = function(){
            return $scope.items.length;
        }

        $scope.completedTodo = function(){
            var count = 0;

            angular.forEach($scope.items, function(item){
                count += item.completed ? 0 : 1
            })

            return count
        }

        $scope.isDone = function(done) {
            return (done) ? 'success' : 'danger';
        }
    }
);